package com.example.handsets8app.View.TuLou1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.handsets8app.Base.BaseConfig;
import com.example.handsets8app.Bean.CheckTicketForTulouResponse;
import com.example.handsets8app.Bean.CheckTicketResponse;
import com.example.handsets8app.R;
import com.example.handsets8app.Utils.LogUtil;
import com.example.handsets8app.Utils.SPUtil;
import com.example.handsets8app.Utils.SelfToastUtil;
import com.example.handsets8app.Utils.StringUtil;
import com.example.handsets8app.Utils.TimeUtil;
import com.example.handsets8app.Utils.util;
import com.example.handsets8app.View.NewXinZhongXinActivity;
import com.google.gson.Gson;
import com.synjones.handsetS8L.ScanDevice;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.reader.IDCardReaderModule;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;

public class TuLouMainActivity extends AppCompatActivity {

    //语音的引入
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    private long timeNew;
    private long timeOld;
    private String OldID;

    //引入读取身份证，  新中心

    private boolean reading = false;
    public IDCardReaderModule idCardReaderModule;

    private String barcodeStr;
    ScanDevice sm;
//    private Button btIdCheck;

    private Timer timer;
    private boolean isReadingCard = false;
    private ReadCardThread ReadCardThreadhandler;
    private static final int UpDateTime = 0x04;
    private static final int ReadOnceDone = 0x01;
    private String status = "";
    private static final int ReadThreadDone = 0x09;
    private static final int ReadScan = 0x11;

    public static final int SCAN_IDCARD_REQUEST = 1;
    private final static String SCAN_ACTION = "scan.rcv.message";


    private String url;
    private String myname;
    private String mypwd;
    private String gateno;
    private String ICcardno;//二维码号码
    private TextView tvGateNo;
    private TextView tvTicketNo;
    private TextView tvState;
    private TextView tvTicketName;
    private TextView tvGPassNumber;
    private String ticketNo;
    private String certificateNo;
    private EditText etIDHand;
    private Button btIDHand;


    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {

                Log.i("zyf", "onInit: TTS引擎初始化成功");
            } else {
                Log.i("zyf", "onInit: TTS引擎初始化失败");
            }
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ReadScan:
                    String ScanNumber = (String) msg.obj;
                    timeNew = TimeUtil.getLocationTimeLong();
                    if (!checkIDAgain(ScanNumber)) {
                        PlayAudioFile("请稍等");
                        HttpURL(1, ScanNumber);
                    }
                    break;
                case ReadOnceDone:
                    //身份证新中新 手持机  身份证
                    IDCard idCard = (IDCard) msg.obj;
                    timeNew = TimeUtil.getLocationTimeLong();
                    if (!checkIDAgain(idCard.getIDCardNo())) {
                        PlayAudioFile("请稍等");
                        HttpURL(2, idCard.getIDCardNo());
                    }
                    break;

            }

        }
    };

    private void HttpURL(final int type, final String scanNumber) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                timeNew = TimeUtil.getLocationTimeLong();

                    send(type, scanNumber);

            }
        }).start();
    }



    public boolean send(int type, final String searchNumber) {

        tvGateNo.setText(gateno);
        tvTicketNo.setText(searchNumber);
        try {
            String sendUrl = url + "checkTicketInterface/checkTicket.do";
            //String sendUrl = "http://122.4.248.213:80/checkTicketInterface/checkTicket.do";

            String icCardNo = ICcardno;
            if (type == 1) {
                ticketNo = searchNumber;
                certificateNo = "";
            } else if (type == 2) {
                 ticketNo = "";
                 certificateNo = searchNumber;
            }


            Map<String, String> map = new HashMap<String, String>();
            map.put("ticketNo", ticketNo);
            map.put("certificateNo", certificateNo);
            map.put("cardNo", icCardNo);
            map.put("userName", myname);
            map.put("password", mypwd);
            map.put("gateNo", gateno);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);

            String sendDate = "ticketNo=" + ticketNo + "&certificateNo=" + certificateNo
                    + "&cardNo=" + icCardNo + "&userName=" + myname + "&password=" + mypwd
                    + "&gateNo=" + gateno + "&sign=" + sign;
            //String sendDate = "ticketNo=" + ticketNo + "&certificateNo=" + certificateNo + "&userName=" + myname + "&password=" + mypwd + "&gateNo=" + gateno + "&sign=" + sign;
            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            //将String类型转换成json类型
            JSONObject object = null;
            try {
                object = XML.toJSONObject(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String jsonData = object.toString();        //转换为json字符串。
            Log.d("", "" + jsonData);
            final CheckTicketForTulouResponse response1 = new Gson().fromJson(result, CheckTicketForTulouResponse.class);

            final int status = Integer.parseInt(response1.getCode());


            switch (status) {
                case 0:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            tvState.setText(response1.getMsg());
                            tvTicketName.setText(response1.getTicketName());
                            tvGPassNumber.setText(String.valueOf(response1.getTotalMaxNumber()));
                            PlayAudioFile( response1.getTicketName()+ response1.getMsg() + "可通行" +response1.getTotalMaxNumber() + "人");
//                            Ticketstatue.setText(response1.getCheckTicketMessageResult().getMsg());
//                            TicketName.setText(response1.getCheckTicketMessageResult().getTicketName());
//                            TicketNumeber.setText(String.valueOf(response1.getCheckTicketMessageResult().getTotalMaxNumber()));
//                            TicketTime.setText(response1.getCheckTicketMessageResult().getCheckTime());
//                            if (status == 0) {
//
//                                iCheckNO += response1.getCheckTicketMessageResult().getTotalMaxNumber();//累加人数
//                            }
//                            CheckNOStr.setText(String.valueOf(iCheckNO));
                        }
                    });
                    break;
                default:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            PlayAudioFile(response1.getMsg());
                            SelfToastUtil.getInstance().show(response1.getMsg());
                        }
                    });

//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
////                            if (mCustomPopWindow != null) {
////                                mCustomPopWindow.dissmiss();
////                                mCustomPopWindow=null;
////                                showPopTopWithDarkBg_checked(response1);
////
////                            } else {
////                            }
//                            showPopTopWithDarkBg_checked(response1);
//                        }
//                    });

                    break;
            }


//            String soundid = getxmlstr1(result, "gateSoundID");
//            String pathsound = "/storage/sdcard0/sound/" + response1.getCheckTicketMessageResult().getGateSoundId() + ".wav";
//            play(pathsound);


        } catch (Exception e) {

            SelfToastUtil.getInstance().show("检票异常:" + e.getMessage());
            return false;
        } finally {

        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tu_lou_main);

        //*获取Intent中的Bundle对象*//*
        Bundle bundle = getIntent().getExtras();
        url = getIntent().getStringExtra("url");
        myname = getIntent().getStringExtra("myname");
        mypwd = getIntent().getStringExtra("mypwd");
        gateno = getIntent().getStringExtra("gateno");

//        btIdCheck = findViewById(R.id.bt_check_id);

        tvGateNo = findViewById(R.id.ma_tv_terminal);
        tvTicketNo = findViewById(R.id.ma_tv_ticketNO);
        tvState = findViewById(R.id.ma_tv_status);
        tvTicketName = findViewById(R.id.ma_tv_name);
        tvGPassNumber = findViewById(R.id.ma_tv_people);

        etIDHand = findViewById(R.id.et_id_number_hands);
        btIDHand = findViewById(R.id.bt_check_id_hands);

        //获取TTS引擎
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }

        // 身份证引入
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        //带nfc的机器需要关闭nfc才可以读身份证
        if (idCardReaderModule.hasNfc(this)) {
            idCardReaderModule.closeNFC();
        }

        // 二维码引入
        sm = new ScanDevice();
        sm.setOutScanMode(0);//启动就是广播模式
        doThing();
    }

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);

        // 启动 身份证
        startReadThread();
        sm.openScan();
    }

    private void doThing() {

//        btIdCheck.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                // 新中心 读取身份证 代码
//                if (timer != null) {
//                    timer.cancel();
//                }
//                timer = null;
//
//                cleanFace();
//                //新中新 手持机 的读取身份证检票           isReadingCard = false;
//                if (!isReadingCard){
//                    PlayAudioFile("开始身份证验票");
//                    startReadThread();
//                }else {
//                    PlayAudioFile("身份证验票中，请勿重复点击");
//                }
//            }
//        });

        btIDHand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isNullOrEmpty(etIDHand.getText().toString())) {
                    SelfToastUtil.getInstance().show("请输入身份证号码");
                    PlayAudioFile("请输入身份证号码");
                    return;
                }else {
                    timeNew = TimeUtil.getLocationTimeLong();
                    if (!checkIDAgain(etIDHand.getText().toString()))
                        PlayAudioFile("请稍等");
                    HttpURL(2, etIDHand.getText().toString());

                }
            }
        });

    }

    //清楚数据，
    private void cleanFace() {

    }

    public static String sendPost(String sendUrl, String param) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            // 获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    /**
     * 生成签名结果
     *
     * @param sArray 要签名的数组
     * @param key    通知密钥
     * @return 签名结果字符串
     */
    public static String buildMysign(Map<String, String> sArray, String key) {
        try {
            Map<String, String> result = paraFilter(sArray);
            String prestr = createLinkString(result); //把数组所有元素，按照“参数参数值”的模式拼接成字符串
            prestr = key + prestr; //把接口密钥+拼接后的字符串直接连接起来
            String mysign = md5(prestr);
            if (mysign != null) {
                mysign = mysign.toUpperCase();
                System.out.println(mysign);
            }
            return mysign;
        } catch (Exception e) {

        }
        return null;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数参数值”的模式拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            prestr = prestr + key + value;
        }
        return prestr;
    }


    private void startReadThread() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();

    }

    //读卡线程
    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            if (!idCardReaderModule.isOpen()) {
                reading = false;
                idCardReaderModule.close();
                Log.e("ReadCardThread", "读卡器打开失败");
            }
            new UpdateTimerThread().start();

            while (reading) {
                try {
                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
                    IDCardReaderRetInfo retInfo;
//                    if (!boolReadFringerprint)//是否需要读指纹
//                        retInfo = idCardReaderModule.getIDcardInfo();
//                    else
                    retInfo = idCardReaderModule.getIDcardInfo(false, false, false);

                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
                    if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
                        //if(boolReadFringerprint)//仅测试时读取追加信息
                        //	retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
                        mHandler.obtainMessage(ReadOnceDone, retInfo.card).sendToTarget();
                        status = "";
                        Thread.sleep(500);
                    } else if (retInfo.errCode == IDCardReaderRetInfo.ERROR_RECV_FINDCARD) {
                        Log.e("ReadCardThread", "通信错误,重新打开读卡器");
                        idCardReaderModule.close();
                        Thread.sleep(3000);
                        idCardReaderModule.open();
                        if (!idCardReaderModule.isOpen()) {
                            reading = false;
                            idCardReaderModule.close();
                            Log.e("ReadCardThread", "读卡器打开失败");
                        }
                    } else {
                        status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
                        mHandler.obtainMessage(ReadOnceDone, null).sendToTarget();
                        Thread.sleep(200);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }//while

            mHandler.obtainMessage(ReadThreadDone).sendToTarget();

        }//run

        public void StopRead() {
            reading = false;
            interrupted();
        }

    }

    class UpdateTimerThread extends Thread {
        public void run() {
            while (reading) {
                mHandler.obtainMessage(UpDateTime).sendToTarget();
                util.sleep(1000);
            }
        }
    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器 身份证
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        stopRead();
        idCardReaderModule.close();
    }

    private void stopRead() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            try {
                ReadCardThreadhandler.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ReadCardThreadhandler = null;
        }
    }

    // 返回 true  相同 小于  30 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 5) {
            System.out.println("zyf  未超过10秒 拒绝访问" + TimeUtil.getLocationTime());
//            PlayAudioFile("相同身份证30秒内拒绝二次检票");
            return true;
        } else {
            System.out.println("zyf  超过10秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            byte[] barocode = intent.getByteArrayExtra("barocode");
            int barocodelen = intent.getIntExtra("length", 0);
            byte temp = intent.getByteExtra("barcodeType", (byte) 0);
            byte[] aimid = intent.getByteArrayExtra("aimid");
            barcodeStr = new String(barocode, 0, barocodelen);
            mHandler.obtainMessage(ReadScan, barcodeStr).sendToTarget();
            sm.stopScan();
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
//        isReadingCard = false;
        unregisterReceiver(mScanReceiver);
        stopRead();
        CloseReader();
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i("zyf", "中文设置失败");
        } else {
            Log.i("zyf", "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
    }
}
